<?php
declare(strict_types=1);
namespace app\admin\model;
use aphp\core\Model;
class ModelField extends Model
{
	protected string $table = 'model_field';
	protected string $pk = 'id';
    protected array $validate = [
        ['field_title', 'required', '字段标题必须', IF_MUST, AC_BOTH],
        ['field_name', '/^\w{2,20}$/|unique', '字段名称格式错误|字段名称已存在', IF_MUST, AC_BOTH],
        ['sort', 'number', '排序值必须是数字', IF_MUST, AC_BOTH],
    ];
    protected array $auto = [
        ['field_name', 'strtolower', 'function', IF_MUST, AC_BOTH],
        ['field_comment', 'field_title', 'field', IF_EMPTY, AC_BOTH],
        ['status', '1', 'string', IF_MUST, AC_INSERT],
    ];

    protected function _validate_where(array $data): array
    {
        return ['model_id' => $data['model_id']];
    }

    // 获取表名
    private function _get_table(int $model_id): string
    {
        $model = db('model')->where('id', $model_id)->field('table_name,table_prefix')->find();
        return $model['table_prefix'].$model['table_name'];
    }

    // 删除字段
    protected function _after_delete(array $data): void
    {
        $table = $this->_get_table($data['model_id']);
        $is_table = $this->db->query("SHOW TABLES LIKE '$table'"); // 判断表是否存在
        if (!empty($is_table)) {
            $is_field = $this->db->query("SHOW COLUMNS FROM `$table` LIKE '{$data['field_name']}'");
            if (!empty($is_field)) {
                $this->db->execute("ALTER TABLE `{$table}` DROP COLUMN `{$data['field_name']}`;");
                $name = preg_replace('/^.*?_/', '', $table);
                cache('field/' . $name . '_field', null);
            }
        }
    }

    // 更新或追加字段
    protected function _after_update(array $before, array $after): void
    {
        $table = $this->_get_table($after['model_id']); // 获取表名
        $is_table = $this->db->query("SHOW TABLES LIKE '$table'"); // 判断表是否存在
        if (!empty($is_table)) {
            $type = ($after['field_length'] > 0) ? $after['field_type'].'('.$after['field_length'].')' : $after['field_type'];
            $unsigned = '';
            if ($after['is_unsigned'] && !in_array($after['field_type'], ['varchar', 'char', 'text'])) {
                $unsigned = ' UNSIGNED';
            }
            $not_null = $after['is_required'] ? ' NOT NULL' : ' NULL';
            $default = '';
            if ($after['field_value'] == 'null') {
                if (!$after['is_primary']) {
                    $default = ' DEFAULT NULL';
                    $not_null = ' NULL';
                }
            } else {
                $default = " DEFAULT '{$after['field_value']}'";
            }
            $comment = " COMMENT '{$after['field_comment']}'";
            // 判断表字段是否存在
            $is_field = $this->db->query("SHOW COLUMNS FROM `$table` LIKE '{$before['field_name']}'");
            if (!empty($is_field)) {
                // 更新字段
                $sql = "ALTER TABLE `{$table}` CHANGE `{$before['field_name']}` `{$after['field_name']}` ".$type.$unsigned.$not_null.$default.$comment.";";
            } else {
                // 追加字段
                $field_list = $this->db->where('model_id', $after['model_id'])->where('status=1')->order('sort ASC,id ASC')->column('field_name', 'id');
                [$prev_id, ] = get_prev_next($after['id'], array_keys($field_list));
                $after_field = isset($field_list[$prev_id]) ? ' AFTER `'.$field_list[$prev_id].'`' : '';
                $sql = "ALTER TABLE `{$table}` ADD COLUMN `{$after['field_name']}`".$type.$unsigned.$not_null.$default.$comment.$after_field.";";
            }
            $this->db->execute($sql);
            $name = preg_replace('/^.*?_/', '', $table);
            cache('field/' . $name . '_field', null);
        }
    }

}